const Common = function () {
    // ajax基本封装
    function ajaxSend(url, data, async, type, dataType, contentType, successfn, errorfn) {
        async = (async == null || async === "" || typeof (async) == "undefined") ? "true" : async;
        type = (type == null || type === "" || typeof (type) == "undefined") ? "GET" : type;
        dataType = (dataType == null || dataType === "" || typeof (dataType) == "undefined") ? "json" : dataType;
        contentType = (contentType == null || contentType === "" || typeof (contentType) == "undefined") ? "application/x-www-form-urlencoded;charset=UTF-8" : contentType;
        $.ajax({
            type: type,
            url: url,
            data: data,
            dataType: dataType,
            contentType: contentType,
            async: async,
            success: function (res) {
                if (res.value === 403) {
                    layer.msg(res.message, {icon: 2, time: 1000}, function () {
                        window.location.href = ctx + "/loginPage";
                    });
                } else if (res.value === 401) {
                    layer.msg(res.message, {icon: 2, time: 1000});
                } else {
                    successfn(res);
                }
            },
            error: function (e) {
                if (errorfn) {
                    errorfn(e);
                }
            }
        });
    }

    // layui table封装
    function layuiTable(tableObj, elem, url, method, cols, where, doneCallBack, toolbar) {
        method = getDefaultValue(method, "get");
        toolbar = getDefaultValue(toolbar, true);
        where = getDefaultValue(where, {});
        return tableObj.render({
            elem: elem
            , url: url
            , method: method
            , cols: cols
            , where: where
            , toolbar: toolbar
            , page: {
                limits: [10, 20, 50, 100]
            }
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.value, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.content //解析数据列表
                };
            }
            , response: {
                // statusName: 'status', //规定数据状态的字段名称，默认：code
                statusCode: 200 //规定成功的状态码，默认：0
                // ,msgName: 'hint' //规定状态信息的字段名称，默认：msg
                // ,countName: 'total' //规定数据总数的字段名称，默认：count
                // ,dataName: 'rows' //规定数据列表的字段名称，默认：data
            }
            , request: {
                pageName: 'currentPage' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , done: function (res, curr, count) {
                // done - 数据渲染完的回调 res是layui的parseData
                if (res.code === 403) {
                    layer.msg(res.message, {icon: 2, time: 1000}, function () {
                        window.location.href = ctx + "/loginPage";
                    });
                } else if (res.code === 401) {
                    layer.msg(res.message, {icon: 2, time: 2000});
                } else {
                    if (doneCallBack && typeof (doneCallBack) === "function") {
                        doneCallBack(res);
                    }
                }
            }
        });
    }

    function getParams($form) {
        const params = {};
        // item为arr的元素，index为下标，arr原数组
        $form.serializeArray().forEach((item, index, arr) => {
            if (null != item.value && "" !== item.value) {
                params[item.name] = item.value;
            }
        });
        return params;
    }

    function reloadTable($form, table) {
        const params = getParams($form);
        table.reload({
            where: {condition: params}
            , page: {
                currentPage: 1
            }
        });
    }

    // https://www.layui.com/doc/modules/layer.html
    function openFrame(content, title, area, offset, maxmin, endFn) {
        area = area === undefined ? ['600px', '450px'] : area;
        offset = offset === undefined ? ['50px', '300px'] : offset;
        maxmin = maxmin === undefined ? false : maxmin;
        return layer.open({
            type: 2
            , title: title
            , content: content
            , area: area
            , offset: offset
            , maxmin: maxmin
            , end: function () {
                if (endFn && typeof (endFn) === 'function') {
                    endFn();
                }
            }
        });
    }

    // https://www.layui.com/doc/modules/layer.html#btn
    function openFrameBtn(content, title, area, offset, btn, maxmin, endFn) {
        area = area === undefined ? ['600px', '450px'] : area;
        offset = offset === undefined ? ['50px', '300px'] : offset;
        btn = btn === undefined ? ['确定', '取消'] : btn;
        maxmin = maxmin === undefined ? false : maxmin;
        return layer.open({
            type: 2
            , title: title
            , content: content
            , area: area
            , offset: offset
            , btn: btn
            , maxmin: maxmin
            , yes: function (index, layero) {
                debugger;
                //按钮【按钮一】的回调
            }
            , btn2: function (index, layero) {
                debugger;
                //按钮【按钮二】的回调
                //return false 开启该代码可禁止点击该按钮关闭
            }
            , cancel: function () {
                //右上角关闭回调
                //return false 开启该代码可禁止点击该按钮关闭
            }
            , end: function () {
                if (endFn && typeof (endFn) === 'function') {
                    endFn();
                }
            }
        });
    }

    function closeFrame() {
        //当你在iframe页面关闭自身时
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index); //再执行关闭
    }

    //https://www.layui.com/doc/modules/upload.html#options
    function upload(uploadObj, elem, url, method, data, accept, acceptMime, exts, field, size, multiple, number, drag, done, error) {
        method = getDefaultValue(method, "post");
        data = getDefaultValue(data, {});
        accept = getDefaultValue(accept, "images");
        acceptMime = getDefaultValue(acceptMime, "images");
        exts = getDefaultValue(exts, "jpg|png|gif|bmp|jpeg");
        field = getDefaultValue(field, "file");
        size = getDefaultValue(size, 0);
        multiple = getDefaultValue(multiple, false);
        number = getDefaultValue(number, 0);
        drag = getDefaultValue(drag, true);
        return uploadObj.render({
            elem: elem
            , url: url
            , method: method
            , data: data
            , accept: accept
            , acceptMime: acceptMime
            , exts: exts
            , field: field
            , size: size
            , multiple: multiple
            , number: number
            , drag: drag
            , done: function (res, index, upload) {
                if (done && typeof (done) === "function") {
                    done(res, index, upload);
                }
            }
            , error: function (index, upload) {
                if (error && typeof (error) === "function") {
                    error(index, upload);
                }
            }
        })
    }

    function getDefaultValue(value, defaultValue) {
        return (value == null || value === "" || typeof (value) == "undefined") ? defaultValue : value;
    }

    function layerPhotos(layerObj, photosJson, closeBtn, shade, anim) {
        closeBtn = getDefaultValue(closeBtn, 1);
        shade = getDefaultValue(shade, 0.3);
        anim = getDefaultValue(anim, 0);
        layerObj.photos({
            photos: photosJson
            , closeBtn: closeBtn
            , shade: shade
            , anim: anim
        });
    }

    //https://www.layui.com/doc/modules/colorpicker.html
    function colorpicker(colorpickerObj, elem, color, format, alpha, predefine, colors, size, change, done) {
        color = getDefaultValue(color, 'rgba(7, 155, 140, 1)');
        format = getDefaultValue(format, "hex");
        alpha = getDefaultValue(alpha, false);
        predefine = getDefaultValue(predefine, false);
        colors = getDefaultValue(colors, []);
        size = getDefaultValue(size, 'lg');
        return colorpickerObj.render({
            elem: elem
            , color: color
            , format: format
            , alpha: alpha
            , predefine: predefine
            , colors: colors
            , size: size
            , change: function (color) {
                if (change && typeof (change) === "function") {
                    change(color);
                }
            }
            , done: function (color) {
                if (done && typeof (done) === "function") {
                    done(color);
                }
            }
        });
    }

    return {
        ajax: function (url, data, async, type, dataType, contentType, successfn, errorfn) {
            ajaxSend(url, data, async, type, dataType, contentType, successfn, errorfn);
        },
        ajaxGet: function (url, data, successfn, errorfn) {
            ajaxSend(url, data, true, "GET", "json", 'application/x-www-form-urlencoded;charset=UTF-8', successfn, errorfn);
        },
        ajaxGetNoParams: function (url, successfn, errorfn) {
            ajaxSend(url, {}, true, "GET", "json", 'application/x-www-form-urlencoded;charset=UTF-8', successfn, errorfn);
        },
        ajaxPost: function (url, data, successfn, errorfn) {
            ajaxSend(url, data, true, "POST", "json", 'application/x-www-form-urlencoded;charset=UTF-8', successfn, errorfn);
        },
        ajaxPostJSON: function (url, data, successfn, errorfn) {
            ajaxSend(url, data, true, "POST", "json", 'application/json;charset=UTF-8', successfn, errorfn);
        },
        ajaxPut: function (url, data, successfn, errorfn) {
            ajaxSend(url, data, true, "PUT", "json", 'application/x-www-form-urlencoded;charset=UTF-8', successfn, errorfn);
        },
        ajaxPutJSON: function (url, data, successfn, errorfn) {
            ajaxSend(url, data, true, "PUT", "json", 'application/json;charset=UTF-8', successfn, errorfn);
        },
        ajaxDelete: function (url, data, successfn, errorfn) {
            ajaxSend(url, data, true, "DELETE", "json", 'application/x-www-form-urlencoded;charset=UTF-8', successfn, errorfn);
        },
        ajaxDeleteNoParams: function (url, successfn, errorfn) {
            ajaxSend(url, {}, true, "DELETE", "json", 'application/x-www-form-urlencoded;charset=UTF-8', successfn, errorfn);
        },
        layuiTable: function (tableObj, elem, url, method, cols, where, doneCallBack, toolbar) {
            return layuiTable(tableObj, elem, url, method, cols, where, doneCallBack, toolbar);
        },
        getLayuiTable: function (tableObj, elem, url, cols, where) {
            return layuiTable(tableObj, elem, url, "get", cols, where);
        },
        postLayuiTable: function (tableObj, elem, url, cols, where) {
            return layuiTable(tableObj, elem, url, "post", cols, where);
        },
        reloadTable: function ($form, table) {
            reloadTable($form, table);
        },
        openFrame: function (content, title, endFn) {
            openFrame(content, title, ['600px', '450px'], ['50px', '300px'], false, endFn);
        },
        openFrameArea: function (content, title, area, endFn) {
            openFrame(content, title, area, ['20px', '300px'], false, endFn);
        },
        openFrameAll: function (content, title, area, offset, maxmin, endFn) {
            openFrame(content, title, area, offset, maxmin, endFn);
        },
        openFrameBtn: function (content, title, endFn) {
            openFrameBtn(content, title, ['600px', '450px'], ['50px', '300px'], ['确定', '取消'], false, endFn);
        },
        openFrameBtnAll: function (content, title, area, offset, btn, maxmin, endFn) {
            openFrameBtn(content, title, area, offset, btn, maxmin, endFn);
        },
        closeFrame: function () {
            closeFrame();
        },
        upload: function (elem, url, method, data, accept, acceptMime, exts, field, size, multiple, number, drag, done, error) {
            return upload(elem, url, method, data, accept, acceptMime, exts, field, size, multiple, number, drag, done, error);
        },
        simpleUpload: function (uploadObj, elem, url, method, done) {
            return upload(uploadObj, elem, url, method, {}, "images", "images", "jpg|png|gif|bmp|jpeg", "file", 0, false, 0, true, done);
        },
        layerPhotos: function (layerObj, photosJson, anim, shade, closeBtn) {
            layerPhotos(layerObj, photosJson, anim, shade, closeBtn);
        },
        simpleLayerPhotos: function (layerObj, photosJson) {
            layerPhotos(layerObj, photosJson);
        },
        colorpicker: function (colorpickerObj, elem, color, format, alpha, predefine, colors, size, change, done) {
            return colorpicker(colorpickerObj, elem, color, format, alpha, predefine, colors, size, change, done);
        },
        simpleColorpicker: function (colorpickerObj, elem, change, done) {
            return colorpicker(colorpickerObj, elem, '-', 'hex', false, false, [], '-', change, done);
        }
    }

}();